package com.liu.juc.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author TOP_LIU
 * @description
 * @date 2021/9/12
 */
public class LockTest {
    public static void main(String[] args) {
        Ticket1 ticket = new Ticket1();

        new Thread(()->{
            for (int i = 0; i<40;i++) {
                ticket.slve();
            }

        },"A").start();

        new Thread(()->{
            for (int i = 0; i<40;i++) {
                ticket.slve();
            }

        },"B").start();

        new Thread(()->{
            for (int i = 0; i<40;i++) {
                ticket.slve();
            }

        },"C").start();
    }
}



//
/**
 *功能描述
 * @author TOP_LIU
 * 1 new ReentrantLock
 * 2 将业务模块放到try cache 中
 * 3 finally = > unlock
 */
class Ticket1 {

    private int number =30;
    Lock lock = new ReentrantLock();
    public   void slve(){

        lock.lock(); //加锁
        try{
            if(number>0){
                System.out.println(Thread.currentThread().getName()
                        + "买了第"+number+"张票" + "剩余" + --number +"张票");
            }
        }catch (Exception e){

        }finally {
            lock.unlock();
        }


    }

}
